﻿using System;
using System.Collections.Generic;
using System.Reflection;
using urn.nhibernate.mapping.Item2.Item2;
using System.Linq;

namespace CccNh.Conventions
{
    public class CreateHiloIdIfTypeHasIntIdField : IClassConvention
    {
        public void Apply(Type type, @class @class, IEnumerable<Type> entityTypes, hibernatemapping mapping)
        {
            var idField = type.GetField("Id", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                          ?? type.GetField("id", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                          ?? type.GetField("_id", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                ;

            if (idField != null)
            {
                @class.id = new id()
                {
                    name = idField.Name,
                    generator = new generator() {@class = "hilo"},
                    column = {new column() {name = "Id"}}
                };
                @class.property.Where(p => p.name == idField.Name).ToList().ForEach(p => @class.property.Remove(p));
            }
        }
    }
}